package org.mozhu.zufang.system.account.service;

import com.google.common.collect.Lists;
import org.mozhu.mboot.core.data.BaseService;
import org.mozhu.mboot.core.data.Searchable;
import org.mozhu.mboot.core.data.filter.Operator;
import org.mozhu.zufang.system.account.entity.User;
import org.mozhu.zufang.system.account.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户 - 业务层实现类
 *
 * @author mozhu
 */
@Transactional
@Service(value = "userService")
public class UserServiceImpl extends BaseService<User, Long> implements UserService {

    @Autowired
    PasswordEncoder passwordEncoder;

    protected UserRepository getBaseRepository() {
        return (UserRepository) baseRepository;
    }

    @Override
    public User findByLoginName(String loginName) {
        return this.getBaseRepository().findByLoginName(loginName);
    }


    @Override
    public User findByName(String name) {
        return this.getBaseRepository().findByName(name);
    }

    @Override
    public User findByMobile(String mobile) {
        return this.getBaseRepository().findByMobile(mobile);
    }

    @Override
    public User findByEmail(String email) {
        return this.getBaseRepository().findByEmail(email);
    }

    @Override
    public void encryptPassword(User user) {
        String plainPassword = user.getPlainPassword();
        String password = passwordEncoder.encode(plainPassword);
        user.setPassword(password);
    }

    @Override
    public Page<User> queryUser(String query, Pageable pageable) {
        Searchable searchable = Searchable.newSearchable(pageable);
        searchable.addSearchFilter(Lists.newArrayList("name", "enName", "loginName", "email"), Operator.LIKE, query);
//        searchable.addSearchFilter("id", Operator.NE, AppUtils.getCurrentUserId());
        searchable.addSearchFilter("deleted", Operator.EQ, Boolean.FALSE);
        return this.getBaseRepository().findAll(searchable);
    }

}
